package gmwxapplet

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogap/logs"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/automate"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/wxpay"
)

func HandleGetAutomateOrderList(ctx *gin.Context) {
	memberId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.GetAutomateOrderListReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.MemberId = memberId

	data := dao.NewAutomateDaoDao().GetWxAutomateOrderList(param)

	Response(ctx)("", CodeSuccess, ResponseConfigList{
		Host:       global.Cfg.Ali.AliossPath,
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
	//Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// HandleShippingAdvice 售货机出货通知
func HandleShippingAdvice(ctx *gin.Context) {
	param := &automate.OrderPayDb{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	param.Status = helper.TypeNumOrderAutomateStatusWaitDone
	param.LogisticsTime = time.Now().Format("2006-01-02 15:04:05")

	// 补货通知
	orderInfo := dao.NewAutomateDaoDao().GetGoodsOrderInfoByTradeNo(param.TradeNo).Unwrap().(*request.GetGoodsOrderInfoByIdRes)
	nParam := &placemodel.PlacesServiceNotification{
		MemberId:         orderInfo.MemberId,
		PlaceId:          orderInfo.PlaceId,
		UserId:           orderInfo.UserId,
		PlaceName:        orderInfo.PlaceName,
		PlaceRoom:        orderInfo.Room,
		DeviceSn:         orderInfo.DeviceSn,
		NotificationType: helper.TypeNumNotificationTypeReplenishment,
		Status:           helper.TypeNumNotificationStatusWait,
		Info:             fmt.Sprintf(`{"title":"售货机补货通知","routesId":%d,"goodsName":"%s"}`, orderInfo.RoutesId, orderInfo.GoodsName),
		Message:          "请在客人退房后，及时补货",
		MemberPhone:      orderInfo.Phone,
	}
	notificationsInfo := logic.NewShWxNotificationsLogic().InitNotificationsData(nParam)
	if notificationsInfo.Id <= 0 {
		logs.Error("HandleShippingAdvice->InitNotificationsData", "notificationsInfo is nil")
	}

	param.NotificationId = notificationsInfo.Id
	if data := dao.NewAutomateDaoDao().UpdateGoodsOrder(param); data.Err != nil {
		Response(ctx)("", CodeInternalServerError, nil)(OK)
		return
	}

	go func() {
		_ = logic.NewOrderLogic().CalAutomateOrderDividends(param.TradeNo)
	}()

	Response(ctx)("", CodeSuccess, true)(OK)
}

func HandleAutomateCreateGoodsOrder(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.CreateStewardOrderReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.ClientIp = ctx.ClientIP()
	param.UserId = userId

	if param.Openid == "" || param.DeviceSn == "" {
		Response(ctx)("参数错误,请重新扫码", CodeError, nil)(OK)
		return
	}

	// 商品校验
	goodsList := dao.NewAutomateDaoDao().GetAutomateGoodsBindList(&request.GetAutomateGoodsBindListReq{
		BaseListReq: request.BaseListReq{PageNo: 1, PageSize: 1},
		DeviceSn:    param.DeviceSn,
		RoutesId:    param.RoutesId,
		Status:      helper.TypeNumCommonStatusTrue,
		GoodsStatus: helper.TypeNumGoodsStatusYesOn,
	}).Unwrap().([]*request.GetAutomateGoodsBindListRes)
	if len(goodsList) == 0 {
		Response(ctx)("商品失效", CodeError, false)(OK)
		return
	}

	param.Key = "automate"
	respData := &wxpay.PayData{}
	resultData := &wxpay.PayData{}
	orderLogic := logic.NewOrderLogic()

	if goodsList[0].Price > 0 {
		param.Amount = goodsList[0].Price
		if respData, err = orderLogic.HandleWxStewardUnifiedOrder(param); err != nil {
			Response(ctx)(err.Error(), CodeError, respData)(OK)
			return
		}
		resultData = orderLogic.HandleMakeSign(respData)
		_ = orderLogic.HandleWxStewardSetAgainOrder(orderLogic.TradeNo, resultData.ToJson())
	}

	insertInfo := &automate.OrderDb{
		MemberId:       userId,
		UserId:         goodsList[0].UserId,
		PlaceId:        goodsList[0].PlaceId,
		AutomateGoodId: goodsList[0].AutomateGoodsId,
		Price:          goodsList[0].Price,
		Amount:         goodsList[0].Price,
		BuyNum:         1,
		RoutesId:       goodsList[0].RoutesId,
		Status:         1,
		PayType:        2,
		PlaceName:      goodsList[0].PlaceName,
		TradeNo:        orderLogic.TradeNo,
		DeviceSn:       param.DeviceSn,
		GoodsName:      goodsList[0].Name,
		GoodsIcon:      goodsList[0].Icon,
	}
	if data := dao.NewAutomateDaoDao().InsertGoodsOrder(insertInfo); data.Err != nil {
		Response(ctx)(data.Err.Error(), CodeInternalServerError, respData)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, map[string]interface{}{
		"pay":     resultData.ToJson(),
		"tradeNo": orderLogic.TradeNo,
		"donePay": param.Amount <= 0,
	})(OK)
}

// HandleGetAutomateGoodsList 查询售货机商品
func HandleGetAutomateGoodsList(ctx *gin.Context) {
	param := &request.GetAutomateGoodsBindListReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.GoodsStatus = helper.TypeNumGoodsStatusYesOn
	//param.Status = helper.TypeNumCommonStatusTrue
	if param.DeviceSn == "" {
		Response(ctx)("", CodeInvalidParam, nil)(OK)
		return
	}

	data := dao.NewAutomateDaoDao().GetAutomateGoodsBindList(param)
	Response(ctx)("", CodeSuccess, ResponseConfigList{
		Host:       global.Cfg.Ali.AliossPath,
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
	//Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}
